package com.qianya.oa.controller.activiti.explorer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qianya.oa.annotation.CustomTaskListener;
import com.qianya.oa.common.core.domain.entity.SysUser;
import com.qianya.oa.constant.FormEnum;
import com.qianya.oa.domain.SysPost;
import com.qianya.oa.service.SysPostService;
import com.qianya.oa.service.SysUserService;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/activiti-explorer")
public class ModelController {

    protected static final Logger LOGGER = LoggerFactory.getLogger(ModelController.class);

    @Resource
    private RepositoryService repositoryService;

    @Autowired
    private ObjectMapper objectMapper;

    @Resource
    private SysPostService sysPostService;

    @Resource
    private SysUserService sysUserService;

    /**
     * 获取表单key以及name列表
     *
     * @return
     */
    @RequestMapping(value = "/formList", method = RequestMethod.GET, produces = "application/json")
    public List<HashMap<String, String>> getFormList() {
        return FormEnum.getList();
    }

    /**
     * 获取任务监听器列表
     *
     * @return
     */
    @RequestMapping(value = "/taskListenerList", method = RequestMethod.GET, produces = "application/json")
    public List<HashMap<String, String>> getTaskListenerList() {
        //反射工具包，指明扫描路径
        Reflections reflections = new Reflections("com.qianya.oa.listener");
        //获取带CustomTaskListener注解的类
        Set<Class<?>> taskListenerLass = reflections.getTypesAnnotatedWith(CustomTaskListener.class);
        List<HashMap<String, String>> resultList = new ArrayList<>();
        for (Class<?> aClass : taskListenerLass) {
            HashMap<String, String> map = new HashMap<>();
            //拿到对应的注解，获取自己想要的信息
            CustomTaskListener nameAnnotation = aClass.getAnnotation(CustomTaskListener.class);
            Service valueAnnotation = aClass.getAnnotation(Service.class);
            map.put("name",nameAnnotation.value());
            map.put("value",valueAnnotation.value());
            resultList.add(map);
        }
        return resultList;
    }

    /**
     * 获取岗位列表
     *
     * @return
     */
    @RequestMapping(value = "/postList", method = RequestMethod.GET, produces = "application/json")
    public List<HashMap<String, String>> getPostList() {
        List<SysPost> sysPosts = sysPostService.selectPostAll();

        List<HashMap<String, String>> mapList = new ArrayList<>();
        sysPosts.forEach(e -> {
            HashMap<String, String> map = new HashMap<>();
            map.put("name", e.getPostName());
            map.put("value", e.getPostCode());
            mapList.add(map);
        });

        HashMap<String, String> applicantMap = new HashMap<>();
        applicantMap.put("name", "申请人");
        applicantMap.put("value", "applicant");
        mapList.add(applicantMap);
        return mapList;
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @RequestMapping(value = "/userList", method = RequestMethod.GET, produces = "application/json")
    public List<HashMap<String, String>> getUserList() {
        List<SysUser> sysUsers = sysUserService.selectAllEnabledUser();

        List<HashMap<String, String>> mapList = new ArrayList<>();
        sysUsers.forEach(e -> {
            HashMap<String, String> map = new HashMap<>();
            map.put("name", e.getUserName());
            map.put("value", e.getLoginName());
            mapList.add(map);
        });

        return mapList;
    }

    /**
     * 打开在线编辑器时加载指定模型到页面
     *
     * @param modelId
     * @return
     */
    @RequestMapping(value = "/model/{modelId}/json", method = RequestMethod.GET, produces = "application/json")
    public ObjectNode getEditorJson(@PathVariable String modelId) {
        ObjectNode modelNode = null;

        Model model = repositoryService.getModel(modelId);

        if (model != null) {
            try {
                if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                    modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
                } else {
                    modelNode = objectMapper.createObjectNode();
                    modelNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName());
                }
                modelNode.put(ModelDataJsonConstants.MODEL_ID, model.getId());
                ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(
                        new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
                modelNode.put("model", editorJsonNode);

            } catch (Exception e) {
                LOGGER.error("Error creating model JSON", e);
                throw new ActivitiException("Error creating model JSON", e);
            }
        }
        return modelNode;
    }

    /**
     * 保存流程图编辑器的信息
     *
     * @param modelId
     * @param name
     * @param description
     * @param json_xml
     * @param svg_xml
     */
    @RequestMapping(value = "/model/{modelId}/save", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.OK)
    public void saveModel(@PathVariable String modelId, String name, String description, String json_xml, String svg_xml) {
        try {
            Model model = repositoryService.getModel(modelId);
            ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
            modelJson.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelJson.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            model.setMetaInfo(modelJson.toString());
            model.setName(name);
            model.setDeploymentId(null);
            Integer version = model.getVersion();
            version++;
            model.setVersion(version);
            repositoryService.saveModel(model);
            repositoryService.addModelEditorSource(model.getId(), json_xml.getBytes("utf-8"));
            InputStream svgStream = new ByteArrayInputStream(svg_xml.getBytes("utf-8"));
            TranscoderInput input = new TranscoderInput(svgStream);
            PNGTranscoder transcoder = new PNGTranscoder();
            // Setup output
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);
            // Do the transformation
            transcoder.transcode(input, output);
            final byte[] result = outStream.toByteArray();
            repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
        } catch (Exception e) {
            LOGGER.error("Error saving model", e);
            throw new ActivitiException("Error saving model", e);
        }
    }

    /**
     * 获取流程图编辑器的汉化文件
     *
     * @return
     */
    @RequestMapping(value = "/editor/stencilset", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getStencilset() {
        InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json");
        try {
            return IOUtils.toString(stencilsetStream, "utf-8");
        } catch (Exception e) {
            throw new ActivitiException("Error while loading stencil set", e);
        }
    }
}
